<template>
  <Form
    ref="formComp"
    class="xtx-form"
    :validation-schema="veeValidateSchema"
    v-slot="{ errors }"
  >
    <div class="user-info">
      <img v-if="qqUserInfo.figureurl_2" :src="qqUserInfo.figureurl_2" alt="" />
      <img v-else src="@/assets/images/loading.gif" alt="" />
      <p>
        Hi，{{ qqUserInfo.nickname }}
        欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~
      </p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          v-model="form.mobile"
          name="mobile"
          class="input"
          type="text"
          placeholder="绑定的手机号"
        />
      </div>
      <div class="error">{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          v-model="form.code"
          name="code"
          class="input"
          type="text"
          placeholder="短信验证码"
        />
        <span class="code" @click="sendCode">{{
          time === 0 ? "发送验证码" : `${time}秒后发送`
        }}</span>
      </div>
      <div class="error">{{ errors.code }}</div>
    </div>
    <a href="javascript:;" class="submit" @click="btnLogin">立即绑定</a>
  </Form>
</template>

<script>
import { inject, reactive, ref, onUnmounted } from 'vue'
import veeValidateSchema from '@/utils/vee-validate-schema'
import { Form, Field } from 'vee-validate'
import { useIntervalFn } from '@vueuse/core'
import { userQQBindCode, userQQBindLogin } from '@/api/user.js'
import Message from '@/components/library/Message'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackBind',
  components: {
    Form,
    Field
  },
  setup () {
    const qqUserInfo = inject('qqUserInfo')

    const form = reactive({
      mobile: '',
      code: ''
    })

    const formComp = ref(null)
    const store = useStore()
    const router = useRouter()

    // 倒计时时间
    const time = ref(0)
    // 定义一个计时器
    const { resume, pause } = useIntervalFn(
      () => {
        time.value--
        // 如果为0，倒计时结束
        if (time.value === 0) {
          pause()
        }
      },
      1000,
      { immediate: false }
    )

    // 清除倒计时
    onUnmounted(() => {
      pause()
    })

    // 发送验证码按钮
    const sendCode = async () => {
      // 验证手机号
      const resValidate = veeValidateSchema.mobile(form.mobile)
      // 验证成功
      if (resValidate === true) {
        try {
          // 发请求
          await userQQBindCode(form.mobile)
          Message({ type: 'success', message: '发送成功' })
          // 倒计时开始
          time.value = 60
          resume()
        } catch (error) {
          Message({ type: 'warn', message: error.response.data.message })
        }
      } else {
        // 验证失败,提示用户
        formComp.value.setFieldError('mobile', resValidate)
      }
    }

    const redirectUrl = router.currentRoute.value.query.redirectUrl || '/'
    store.commit('user/setRedirectUrl', redirectUrl)

    // 绑定按钮
    const btnLogin = async () => {
      const res = await formComp.value.validate()
      try {
        let userInfo = null
        if (res && qqUserInfo.value.openId) {
          // 账号登录
          const { result } = await userQQBindLogin({
            unionId: qqUserInfo.value.openId,
            ...form
          })
          userInfo = result

          // 存储信息
          store.commit('user/setUser', userInfo)
          // 跳转
          router.push(store.state.user.redirectUrl)
          Message({ type: 'success', message: '登录成功' })
          // 合并购物车
          store.dispatch('cart/mergeLocalCart')
        } else {
          Message({ type: 'error', message: '验证失败' })
        }
      } catch (error) {
        Message({ type: 'error', message: '手机号或验证码错误' })
      }
    }

    return { qqUserInfo, form, veeValidateSchema, time, sendCode, btnLogin, formComp }
  }
}
</script>

<style scoped lang='less'>
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
